import { defineStore } from "pinia";

export const useFormStore = defineStore("form", {
  state: () => ({
    title: "标题",
    id: "",
    componentList: [],
    selectedId: undefined,
  }),
  getters: {
    treeData: (state) => {
      return state.componentList.map((item) => {
        return {
          key: item.id,
          id: item.id,
          title: item.config.title,
        };
      });
    },
    selectedKeys: (state) => {
      return [state.selectedId];
    },
    selectedItem: (state) => {
      return state.componentList.find((item) => item.id === state.selectedId);
    },
  },
  actions: {
    initData(params) {
      this.title = params.title;
      this.id = params.id;
      this.componentList = params.componentList || [];
    },
    getData() {
      return {
        title: this.title,
        id: this.id,
        componentList: this.componentList,
      };
    },
    addComponent(item) {
      this.componentList.push(item);
      this.selectedId = item.id;
    },
    setSelected(selectedId) {
      this.selectedId = selectedId;
    },
    updateConfig(config) {
      this.selectedItem.config = {
        ...this.selectedItem.config,
        ...config,
      };
    },
  },
});
